import Vue from 'vue'
import Vuex from 'vuex'
import { loginAPI } from '@/api/login'
import Storage from '@/utils/storage'

Vue.use(Vuex)

const store = new Vuex.Store({
  // 开启严格模式 —— 一切数据 的修改 只能 通过 mutation 进行
  strict: true,
  state: {
    token: Storage.get('token'),
    refreshToken: Storage.get('refresh_token'),
    userInfo: {
      name: '',
      photo: Storage.get('photo')
    }
  },
  mutations: {
    setToken (state, tokenStr) {
      state.token = tokenStr
      Storage.set('token', tokenStr)
    },
    setRefreshToken (state, refreshTokenStr) {
      state.refreshToken = refreshTokenStr
      Storage.set('refresh_token', refreshTokenStr)
    },
    setUserInfo (state, userObj) {
      state.userInfo = userObj
    },
    setUserName (state, val) {
      state.userInfo.name = val
    },
    setUserPhoto (state, val) {
      state.userInfo.photo = val
      Storage.set('photo', val)
    }
  },
  actions: {
    async asyncLoginAction (store, formLogin) {
      // 1. 发送登录请求
      const resp = await loginAPI(formLogin)
      const { token, refresh_token: refreshToken } = resp.data
      // 2. 提交到mutation - 同步token 和 refreshToken
      store.commit('setToken', token)
      store.commit('setRefreshToken', refreshToken)
    }
  },
  modules: {
  }
})

export default store
